import axios from 'axios'
import { Notification } from 'element-ui'
import store from '../store'
import GLOBAL from '../assets/js/const/global'
import { isNull } from "../assets/js/utils/validate";


const service = axios.create({
  // baseURL: store.state.config.login.serverUrl,
  timeout: 5000,
  headers: {
    'content-type': 'application/json'
  }
})

// 设置请求头
service.interceptors.request.use(
  config => {
    config.baseURL = store.state.config.login.serverUrl
    if (isNull(config.baseURL)) {
      // Notification.error({
      //   offset: 60,
      //   duration: '2000',
      //   title: '提示',
      //   message: '服务器地址为空,请配置登录!'
      // })
    }
    config.headers.authorization = GLOBAL.LOGIN.TOKEN_PREFIX + store.state.config.login.accessToken
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  response => {
    // 校验Http状态码
    const status = response.status
    if (status === 200) {
      return response.data // 部分接口返回code和message，需要自行判断结果
    }
  },
  error => {
    let errMsg;
    // 服务器错误
    if (error.response.data.code) {
      // 登陆过期,请重新登录
      if (error.response.data.code === 41003) {
        store.commit('SET_LOGIN_STATE', GLOBAL.LOGIN.STATE.NONE)
        store.commit('CLEAR_CACHE_TOKEN')
      }
      errMsg = '[' + error.response.data.code + '] ' + error.response.data.msg
    // 非有效服务器错误
    } else {
      errMsg = '服务器连接错误,请检查服务器地址.'
    }
    Notification.error({
      offset: 40,
      duration: 2000,
      position: 'bottom-right',
      title: '(,,#ﾟДﾟ)',
      message: errMsg
    })
    return Promise.reject(error)
  }
)

export default service
